package com.jiuyun.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
    final  int MAX_FILE_SIZE=1024*1024*4;//4MB
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      this.doPost(req, resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //文件上传后的位置    服务器的运行位置
        String appPath=req.getServletContext().getRealPath("/img");
        System.out.println("运行位置"+appPath);
        //配置上传参数
        DiskFileItemFactory factory=new DiskFileItemFactory();
        //设置内存          设置最大文件上传值     默认2M
        ServletFileUpload upload=new ServletFileUpload(factory);
        //设置字符编码
        upload.setFileSizeMax(MAX_FILE_SIZE);
        upload.setHeaderEncoding("utf-8");
        String fname="";
        try {
            List<FileItem> formItems=upload.parseRequest(req);
            for(FileItem item:formItems){
                if(item.isFormField()){    //文本框
                    //?????
                }else{//文件
                     fname=item.getName();  //iphone.jsp
                    File file=new File(appPath+"/"+fname);
                    //保存文件
                    item.write(file);//存盘
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        req.setAttribute("tupian",fname);
        req.getRequestDispatcher("/file.jsp").forward(req,resp);
    }
}
